package com.neusoft.SPNursingHome.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neusoft.SPNursingHome.dao.MealRecordDao;
import com.neusoft.SPNursingHome.po.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class MealRecordServiceImpl implements MealRecordService {

    @Autowired
    private MealRecordDao dao;

    @Override
    public ResponseBean<List<MealRecord>> listAll() {
        List<MealRecord> list = dao.selectList(new QueryWrapper<>());
        return new ResponseBean<>(list);
    }

    @Override
    public ResponseBean<MealRecord> getById(Integer id) {
        MealRecord mr = dao.selectById(id);
        if (mr == null) {
            return new ResponseBean<>(404, "未找到对应 MealRecord 记录");
        }
        return new ResponseBean<>(mr);
    }
    @Override
    public ResponseBean<IPage<ClientMealInfo>> listByClientAndFilter(
            long page, long size,
            Integer clientId,
            String startDay, String endDay,
            String foodType, String foodName, String mealTime
    ) {
        Page<ClientMealInfo> pager = new Page<>(page, size);
        IPage<ClientMealInfo> result = dao.selectByClientAndFilter(
                pager, clientId, startDay, endDay, foodType, foodName, mealTime
        );
        return new ResponseBean<>(result);
    }


    @Transactional(rollbackFor = Exception.class)
    public ResponseBean<Void> create(MealRecord newRecord) {
        MealRecord existing = dao.selectByUniqueKeys(
                newRecord.getClientId(),
                newRecord.getMealCalendarId(),
                newRecord.getMealCalendarDay()
        );

        if (existing != null) {
            System.out.println("✔️ 找到匹配的已存在记录: ID=" + existing.getMealRecordId());
            System.out.println("  原数量: " + existing.getCount());
            System.out.println("  新数量: " + newRecord.getCount());

            // 合并数量
            int oldCount = existing.getCount();
            int newCount = oldCount + newRecord.getCount();
            existing.setCount(newCount);

            System.out.println("🔢 合并数量: " + oldCount + " + " + newRecord.getCount() + " = " + newCount);

            System.out.println("正在更新记录...");
            int updateResult = dao.updateById(existing);

            if (updateResult == 1) {
                System.out.println("✅ 记录更新成功! 新数量: " + newCount);
                return new ResponseBean<>();
            } else {
                System.out.println("❌ 更新失败! 影响行数: " + updateResult);
                return new ResponseBean<>(500, "更新失败");
            }
        } else {
            System.out.println("⭕ 未找到匹配记录，执行新增操作");
            System.out.println("正在插入新记录...");

            int insertResult = dao.insert(newRecord);

            if (insertResult == 1) {
                System.out.println("✅ 新增记录成功! ID=" + newRecord.getMealRecordId());
                return new ResponseBean<>();
            } else {
                System.out.println("❌ 新增失败! 影响行数: " + insertResult);
                return new ResponseBean<>(500, "新增失败");
            }
        }
    }

    @Override
    public ResponseBean<Void> update(MealRecord record) {
        int rows = dao.updateById(record);
        if (rows != 1) {
            return new ResponseBean<>(500, "MealRecord 更新失败");
        }
        return new ResponseBean<>();
    }

    @Override
    public ResponseBean<Void> deleteById(Integer id) {
        int rows = dao.deleteById(id);
        if (rows != 1) {
            return new ResponseBean<>(500, "MealRecord 删除失败");
        }
        return new ResponseBean<>();
    }
}
